import http.client
import json
import random
import time

# 创建 HTTP 连接（如果是 HTTPS，使用 http.client.HTTPSConnection）
conn = http.client.HTTPConnection("127.0.0.1",19527)

def get_position(code:str)->float:
    try:
        # 发送 GET 请求
        conn.request("GET", "/get_position?code="+code)
        # 获取响应
        response = conn.getresponse()
        # 读取响应内容
        response_data = response.read()
        print(f"Status: {response.status} {response.reason} Response:{response_data.decode("utf-8")}")
        result = json.loads(response_data)
        return float(result[code])
    except Exception as e:
        print("Error:", e)

    finally:
        # 关闭连接
        conn.close()
    return None


def sync_position(code:str,ratio:float)->bool:
    # 请求头和 POST 数据
    head_data = {"Content-Type": "application/json"}
    req_data = json.dumps({
        "code": code,
        "ratio": ratio
    })
    try:
        # 发送 POST 请求
        conn.request("POST", "/sync_position", body=req_data, headers=head_data)
        # 获取响应
        response = conn.getresponse()
        # 读取响应内容
        response_data = response.read()
        print(f"Status: {response.status} {response.reason} Response:{ response_data.decode("utf-8")}")
        result = json.loads(response_data)
        return result["result"] == "Success"
    except Exception as e:
        print("Error:", e)
    finally:
        # 关闭连接
        conn.close()
    return False



if __name__ == "__main__":

    #随机调仓
    while(True):
        #随机生成一个持仓系数
        ratio = (random.random() * 2) - 1 
        sync_position("SHFE.ag2506",ratio)
        time.sleep(1)
        position = get_position("SHFE.ag2506")
        print(position)